<template>
    <!-- 使用该组件应当传入两个参数，
        maxNum：最大值
        changeNum：绑定事件 -->
    <div class="num-box">
        <a @click="handler($event,'minus',-1)">-</a>
        <input type="text" :value="num" @change="handler($event,'change',Number.parseInt($event.target.value))" />
        <a @click="handler($event,'add',+1)">+</a>
    </div>
</template>

<script>
export default {
    name: "num-box",
    data() {
        return {
            num: 1,
        };
    },
    methods: {
        handler(event, type, val) {
            switch (type) {
                case "add":
                    val = this.num < this.maxNum ? 1 : 0;
                    break;
                case "minus":
                    val = this.num > 1 ? -1 : 0;
                    break;
                case "change":
                    if (isNaN(val) || val < 1 || val > this.maxNum) {
                        this.$message({
                            message: "请在正确范围输入数据",
                            type: "warning",
                        });
                        val = 0;
                        event.target.value = this.num;
                    } else {
                        val = val - this.num;
                    }
                    break;
            }
            this.num += val;
            this.$emit("changeNum", val);
        },
    },
    props: ["maxNum"],
};
</script>

<style lang="less" scoped>
.num-box {
    border: 1px solid rgb(224, 224, 224);
    height: 38px;
    width: 150px;
    line-height: 38px;
    margin-top: 21px;
    display: flex;

    input[type="text"] {
        width: 74px;
        height: 38px;
        text-align: center;
        border: none;
        padding: 0;
        outline: none;
        font-size: 16px;
        font: inherit;
    }

    a {
        width: 38px;
        height: 38px;
        text-align: center;
        font-size: 19px;
        font-weight: bold;
        cursor: pointer;
        transition: background-color 0.3s ease;
        user-select: none;
    }

    a:hover {
        background-color: rgb(224, 224, 224);
    }
}
</style>